<template>
  <div class="pan-task-management">
    <!-- 筛选区域 -->

    <!-- 任务统计面板 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <DynamicStatistics :items="statisticsItems" />
    </el-card>

    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 任务列表表格 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="taskList"
          :columns="tableColumns"
          :loading="loading"
          :pagination="pagination"
          selection-type="multiple"
          border
          row-key="id"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-page-change="handlePageChange"
        >
          <template #toolbar-left>
            <el-button type="primary" @click="handleCreateTask">
              新建任务
            </el-button>
            <el-button
              type="primary"
              :disabled="selectedRows.length === 0"
              @click="handleBatchUpdate"
            >
              批量更新
            </el-button>
            <!-- <el-button
              type="success"
              :disabled="selectedRows.length === 0"
              @click="handleExportData"
            >
              导出数据
            </el-button> -->
          </template>
          <template #task_status="{ row }">
            <el-tag :type="getStatusTagType(row.task_status)" size="small">
              {{ getStatusText(row.task_status) }}
            </el-tag>
          </template>

          <template #next_run_time="{ row }">
            <span v-if="row.next_run_time">{{ row.next_run_time }}</span>
            <span v-else class="no-schedule">-</span>
          </template>

          <template #operation="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">
              详情
            </el-button>

            <el-button
              :disabled="row.task_status === 'running'"
              size="small"
              @click="handleEditTask(row)"
            >
              编辑
            </el-button>

            <el-button
              :disabled="row.task_status !== 'running'"
              size="small"
              @click="handlePauseTask(row)"
            >
              暂停
            </el-button>

            <el-button
              :disabled="
                row.task_status !== 'pending' && row.task_status !== 'paused'
              "
              size="small"
              @click="handleResumeTask(row)"
            >
              {{ row.task_status === "pending" ? "执行" : "恢复" }}
            </el-button>

            <el-button
              :disabled="row.task_status === 'running'"
              size="small"
              @click="handleDeleteTask(row)"
            >
              删除
            </el-button>
          </template>
        </DynamicTable>

        <el-empty
          v-if="!loading && taskList.length === 0"
          description="暂无任务数据"
        />
      </div>
    </el-card>

    <!-- 新建/编辑任务弹窗 -->
    <AddEditModal
      v-model="taskModalVisible"
      :task="currentTask"
      :is-edit="isEditMode"
      @save="handleSaveTask"
    />

    <!-- 批量更新弹窗 -->
    <BatchUpdateModal
      v-model="batchUpdateVisible"
      :selected-tasks="selectedRows"
      @confirm="handleBatchUpdateConfirm"
    />

    <!-- 任务详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :task-id="currentTaskId"
      :detail-data="taskDetailData"
      :loading="taskDetailLoading"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import DynamicStatistics from "@/components/DynamicStatistics";
import type { StatisticsItem } from "@/components/DynamicStatistics";
import {
  getPanTasks,
  getPanTasksStatistics,
  pauseTask,
  resumeTask,
  deleteTask,
  batchUpdateTasks,
  updateTaskStatus,
  exportTasks,
  getPanTaskDetail,
  runTask,
} from "../../servers";
// import TaskFormModal from "./components/TaskFormModal.vue";
import BatchUpdateModal from "./components/BatchUpdateModal.vue";
import AddEditModal from "./components/AddEditModal.vue";
import DetailModal from "./components/DetailModal.vue";

// 页面状态
const loading = ref(false);
const taskModalVisible = ref(false);
const batchUpdateVisible = ref(false);
const detailVisible = ref(false);
const isEditMode = ref(false);
const currentTask = ref<any>(null);
const currentTaskId = ref<number | null>(null);
const selectedRows = ref<any[]>([]);
const taskDetailData = ref<any>(null);
const taskDetailLoading = ref(false);

// 任务列表数据
const taskList = ref<
  Array<{
    id: number;
    task_name: string;
    task_code: string;
    task_type: string;
    scenario_type: string;
    scenario_type_text: string;
    main_keyword: string;
    task_status: "running" | "pending" | "paused" | "completed" | "failed";
    next_run_time: string;
    created_time: string;
    last_run_time: string;
    created_by: string;
    statistics: {
      total_scanned: number;
      high_risk_count: number;
      medium_risk_count: number;
      low_risk_count: number;
      confirmed_count: number;
      false_positive_count: number;
    };
  }>
>([]);

// 统计信息
const statistics = reactive({
  total: 0,
  running: 0,
  pending: 0,
  paused: 0,
  completed: 0,
  failed: 0,
  successRate: 0,
});

// 统计项配置（用于 DynamicStatistics 组件）
const statisticsItems = computed<StatisticsItem[]>(() => {
  const completedAndFailed = statistics.completed + statistics.failed;
  const successRate =
    completedAndFailed > 0
      ? ((statistics.completed / completedAndFailed) * 100).toFixed(1)
      : "0.0";

  return [
    {
      label: "总任务",
      value: statistics.total,
      bgColor: "#409eff",
      span: 3,
    },
    {
      label: "运行中",
      value: statistics.running,
      bgColor: "#67c23a",
      span: 3,
    },
    {
      label: "待执行",
      value: statistics.pending,
      bgColor: "#909399",
      span: 3,
    },
    {
      label: "已暂停",
      value: statistics.paused,
      bgColor: "#e6a23c",
      span: 3,
    },
    {
      label: "已完成",
      value: statistics.completed,
      bgColor: "#67c23a",
      span: 3,
    },
    {
      label: "已失败",
      value: statistics.failed,
      bgColor: "#f56c6c",
      span: 3,
    },
    {
      label: "成功率",
      value: `${successRate}%`,
      bgColor: "#409eff",
      span: 3,
    },
  ];
});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  task_name: "",
  main_keyword: "",
  task_status: "",
  scenario_type: "",
  task_type: "",
  start_date: "",
  end_date: "",
  sort_by: "created_time",
  sort_order: "desc",
});

// 场景类型选项
const scenarioOptions = ref([
  { label: "财务", value: "financial" },
  { label: "人事", value: "hr" },
  { label: "商务", value: "business" },
  { label: "技术", value: "technical" },
  { label: "其他", value: "other" },
]);

// 任务类型选项
const taskTypeOptions = ref([
  { label: "标准任务", value: "standard" },
  { label: "自定义任务", value: "custom" },
  { label: "系统任务", value: "system" },
]);

// 任务状态选项
const taskStatusOptions = ref([
  { label: "运行中", value: "running" },
  { label: "待执行", value: "pending" },
  { label: "已暂停", value: "paused" },
  { label: "已完成", value: "completed" },
  { label: "已失败", value: "failed" },
]);

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    placeholder: "请输入任务名称",
  },
  {
    key: "main_keyword",
    name: "主关键词",
    type: "input",
    placeholder: "请输入主关键词",
    col: { span: 4 },
  },
  {
    key: "task_status",
    name: "任务状态",
    type: "select",
    placeholder: "全部状态",
    params: { clearable: true },
    options: taskStatusOptions.value,
  },
  {
    key: "scenario_type",
    name: "场景类型",
    type: "select",
    placeholder: "全部场景",
    params: { clearable: true },
    options: scenarioOptions.value,
  },
  {
    key: "task_type",
    name: "任务类型",
    type: "select",
    placeholder: "全部类型",
    params: { clearable: true },
    options: taskTypeOptions.value,
  },
  // {
  //   key: "start_date",
  //   name: "开始日期",
  //   type: "date",
  //   placeholder: "选择开始日期",
  //   params: { clearable: true },
  // },
  // {
  //   key: "end_date",
  //   name: "结束日期",
  //   type: "date",
  //   placeholder: "选择结束日期",
  //   params: { clearable: true },
  // },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "任务编码",
    prop: "task_code",
    minWidth: 140,
    fixed: "left",
  },
  {
    label: "任务名称",
    prop: "task_name",
    minWidth: 180,
  },
  {
    label: "主关键词",
    prop: "main_keyword",
    minWidth: 120,
  },
  {
    label: "场景",
    prop: "scenario_type_text",
    minWidth: 100,
  },
  {
    label: "状态",
    minWidth: 100,
    align: "center",
    slot: "task_status",
  },
  {
    label: "下次执行",
    minWidth: 140,
    slot: "next_run_time",
  },
  {
    label: "操作",
    width: 320,
    fixed: "right",
    slot: "operation",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取任务列表和统计数据
const fetchTaskList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
      ...values,
    };

    // 处理筛选参数
    if (filterForm.task_name) params.task_name = filterForm.task_name;
    if (filterForm.main_keyword) params.main_keyword = filterForm.main_keyword;
    if (filterForm.task_status) params.task_status = filterForm.task_status;
    if (filterForm.scenario_type)
      params.scenario_type = filterForm.scenario_type;
    if (filterForm.task_type) params.task_type = filterForm.task_type;
    if (filterForm.start_date) params.start_date = filterForm.start_date;
    if (filterForm.end_date) params.end_date = filterForm.end_date;

    const result = await getPanTasks(params);

    // 更新任务列表
    taskList.value = result.data.tasks || [];

    // 处理场景类型文本显示
    taskList.value.forEach((task) => {
      const scenario = scenarioOptions.value.find(
        (opt) => opt.value === task.scenario_type
      );
      task.scenario_type_text = scenario?.label || task.scenario_type;
    });

    // 更新分页信息
    if (result.data.pagination) {
      pagination.total = result.data.pagination.total || 0;
      pagination.currentPage = result.data.pagination.page || 1;
      pagination.pageSize = result.data.pagination.per_page || 20;
    }

    // 获取统计数据
    await fetchStatistics();
  } catch (error: any) {
    ElMessage.error(error?.message || "获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const result = await getPanTasksStatistics();
    const data = result.data;

    // 从 summary 中获取统计数据
    if (data?.summary) {
      statistics.total = data.summary.total_tasks || 0;
      statistics.running = data.summary.running_tasks || 0;
      statistics.pending = data.summary.pending_tasks || 0;
      statistics.paused = data.summary.paused_tasks || 0;
      statistics.completed = data.summary.completed_tasks || 0;
      statistics.failed = data.summary.failed_tasks || 0;
      statistics.successRate = data.summary.success_rate || 0;
    } else {
      // 降级方案：从 group_statistics 中提取
      if (data?.group_statistics && Array.isArray(data.group_statistics)) {
        data.group_statistics.forEach((item: any) => {
          const groupName = item.group_name;
          const count = item.count || 0;
          switch (groupName) {
            case "running":
              statistics.running = count;
              break;
            case "pending":
              statistics.pending = count;
              break;
            case "paused":
              statistics.paused = count;
              break;
            case "completed":
              statistics.completed = count;
              break;
            case "failed":
              statistics.failed = count;
              break;
          }
        });
        statistics.total =
          statistics.running +
          statistics.pending +
          statistics.paused +
          statistics.completed +
          statistics.failed;

        // 计算成功率
        const completedAndFailed = statistics.completed + statistics.failed;
        if (completedAndFailed > 0) {
          statistics.successRate =
            (statistics.completed / completedAndFailed) * 100;
        } else {
          statistics.successRate =
            data?.performance_metrics?.avg_success_rate || 0;
        }
      }
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
    // 如果接口失败，从列表数据计算统计（降级方案）
    calculateStatisticsFromList();
  }
};

// 从列表数据计算统计（降级方案）
const calculateStatisticsFromList = () => {
  // 初始化统计数据
  statistics.total = 0;
  statistics.running = 0;
  statistics.pending = 0;
  statistics.paused = 0;
  statistics.completed = 0;
  statistics.failed = 0;
  statistics.successRate = 0;

  // 统计各状态任务数量
  taskList.value.forEach((task) => {
    statistics.total++;
    switch (task.task_status) {
      case "running":
        statistics.running++;
        break;
      case "pending":
        statistics.pending++;
        break;
      case "paused":
        statistics.paused++;
        break;
      case "completed":
        statistics.completed++;
        break;
      case "failed":
        statistics.failed++;
        break;
    }
  });

  // 计算成功率
  const completedAndFailed = statistics.completed + statistics.failed;
  if (completedAndFailed > 0) {
    statistics.successRate = (statistics.completed / completedAndFailed) * 100;
  }
};

// 获取状态标签类型
const getStatusTagType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    running: "success",
    pending: "info",
    paused: "warning",
    completed: "success",
    failed: "danger",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    running: "运行中",
    pending: "待执行",
    paused: "已暂停",
    completed: "已完成",
    failed: "已失败",
  };
  return textMap[status] || status;
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  Object.keys(filterForm).forEach((key) => {
    filterForm[key as keyof typeof filterForm] =
      key === "sort_by" ? "created_time" : key === "sort_order" ? "desc" : "";
  });
  pagination.currentPage = 1;
  fetchTaskList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchTaskList(values);
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTaskList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTaskList();
};

// 选择相关
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 任务操作
const handleCreateTask = () => {
  isEditMode.value = false;
  currentTask.value = {
    task_name: "",
    main_keyword: "",
    aux_keywords: [],
    scenario_type: "",
    task_type: "standard",
    schedule_enabled: true,
    cron_expression: "0 30 10 * * ?",
    config: {
      max_pages: 3,
      risk_threshold: 80,
      auto_confirm: false,
      notification_enabled: true,
    },
  };
  taskModalVisible.value = true;
};

// 获取任务详情
const fetchTaskDetail = async (taskId: number) => {
  if (!taskId) return;

  taskDetailLoading.value = true;
  try {
    const result = await getPanTaskDetail(taskId);
    taskDetailData.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取任务详情失败");
    taskDetailData.value = null;
  } finally {
    taskDetailLoading.value = false;
  }
};

// 查看详情
const handleViewDetail = async (row: any) => {
  if (row.id) {
    currentTaskId.value = row.id;
    detailVisible.value = true;
    await fetchTaskDetail(row.id);
  } else {
    ElMessage.warning("任务ID不存在");
  }
};

// 编辑任务
const handleEditTask = async (row: any) => {
  if (row.id) {
    isEditMode.value = true;
    // 先获取任务详情，用于编辑
    await fetchTaskDetail(row.id);
    currentTask.value = taskDetailData.value;
    taskModalVisible.value = true;
  } else {
    ElMessage.warning("任务ID不存在");
  }
};

const handlePauseTask = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停任务【${row.task_name}】吗？`,
      "操作确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await pauseTask(row.id, {
      pause_reason: "用户手动暂停",
      paused_by: "admin",
    });

    ElMessage.success(result.message || "任务已暂停");
    fetchTaskList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleResumeTask = async (row: any) => {
  try {
    loading.value = true;

    // 根据任务状态调用不同的接口
    if (row.task_status === "pending") {
      // 待执行状态：使用手动执行接口
      const result = await runTask(row.id, {
        force: false,
        executed_by: "admin",
      });

      ElMessage.success(result.message || "任务已开始执行");
      if (result.data?.execution_id) {
        ElMessage.info(`执行ID: ${result.data.execution_id}`);
      }
    } else if (row.task_status === "paused") {
      // 已暂停状态：使用恢复接口
      const result = await resumeTask(row.id, {
        resume_reason: "用户手动恢复",
        resumed_by: "admin",
      });

      ElMessage.success(result.message || "任务已恢复");
    }

    fetchTaskList();
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

const handleDeleteTask = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务【${row.task_name}】吗？此操作不可恢复`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await deleteTask(row.id, { force: false });

    ElMessage.success(result.message || "任务已删除");
    fetchTaskList();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 保存任务（新增/编辑）
const handleSaveTask = async () => {
  // 保存成功后刷新列表
  taskModalVisible.value = false;
  fetchTaskList();
};

// 批量操作
const handleBatchUpdate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要更新的任务");
    return;
  }
  batchUpdateVisible.value = true;
};

const handleBatchUpdateConfirm = async (result: any) => {
  // 批量更新完成后刷新列表
  batchUpdateVisible.value = false;
  selectedRows.value = [];
  fetchTaskList();
};

// 导出数据
const handleExportData = async () => {
  try {
    const taskCodes = selectedRows.value.map((row) => row.task_code);
    const blob = await exportTasks({ task_codes: taskCodes });

    const url = URL.createObjectURL(blob as any);
    const a = document.createElement("a");
    a.href = url;
    const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
    a.download = `网盘任务列表_${date}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  }
};

// 初始化
onMounted(() => {
  fetchTaskList();
});
</script>

<style scoped lang="scss">
.pan-task-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }
  }

  .filter-card,
  .stats-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .list-operations {
    margin-bottom: 15px;
    padding: 10px 15px;
    background-color: #fff;
    border-radius: 8px;
    border: 1px solid #f0f0f0;

    .operation-left {
      display: flex;
      align-items: center;
      gap: 15px;

      .el-checkbox {
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 300px;
  }

  .no-schedule {
    color: #909399;
    font-size: 14px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
